/**
 * description: 腾讯云上传文件
 */

import { app } from '@/config/env'
import Vue from 'vue'

/* eslint-disable */
/**
 * imageView2/w/300/q/60
 */
const region = 'gz';
const filterImg = ['image/jpeg', 'image/png', 'image/gif'];

const UploadFileByTXY = {
  imgFile: null,
  verifyBase64: null,
  path: '/szajimgs/',
  imgURLdomain: app.domain,
  upload: function ({ id, callback }, clip=false) {
    if(!id) return;
    let self = this,
    el = document.getElementById(id),
    file = null,
    size = null,
    fileName = null,
    fileType = null;
    // 监听file元素改变事件
    el.addEventListener('change',function (e) {
      let date = new Date().getTime() + (Math.random() * 1000000).toFixed(0);
      file = this.files[0];
      // self.imgFile = this.files[0];
      size = file.size;
      fileName = date + '.' + file.name.substr(file.name.lastIndexOf('.') + 1)
      fileType = file.type;
      if (filterImg.indexOf(fileType) < 0) {
        let docTip = '上传支持jpg,png等格式文件上传';
        el.value = '';
        alert(docTip);
        return;
      }
      if (window.FileReader) {
			var fr = new FileReader();
        fr.onload = function(e) {
          var imgBase64 = e.target.result;
          self.verifyBase64 = imgBase64;
          let canvasImg = self.compressImg(imgBase64, size, fileType, self.convertBase64UrlToBlob, uploadImg);
        }
        fr.readAsDataURL(file);
	    }
      let c = ''
      let canvasPopup = ''
      let uploadImg = () => {
        Vue.axiosPost(Vue.api.getUploadSign, { cosPath: self.path + fileName , ...app}).then(json => {
          if (json.code === '0000') { // 请求成功
            let sign = json.data.sign
            // 实例化 cos
            let cos = new CosCloud({
              appid: app.appid,
              bucket: app.bucket,
              region: region,
              getAppSign: function (callback) {
                callback(sign)
              },
              getAppSignOnce: function (callback) {
                callback(sign)
              }
            })
            // 图片上传
            Vue.$vux.loading.show({
              text: '正在上传...'
            })
            cos.uploadFile(successCallBack, errorCallBack, progressCallBack, app.bucket, self.path + fileName, self.imgFile, 1);
          } else { // 请求失败
            alert('获取文件上传签名失败！')
          }
        })
      }
    })

    // 上传成功回调
    let successCallBack = (result) => {
      /*
        data.access_url 生成的文件CDN下载url
        data.source_url 生成的文件COS源站url
        data.url 操作文件的url
        data.resource_path 资源路径. 格式:/appid/bucket/xxx
      */
      // Vue.$vux.loading.hide()
      if (result.code === 0) {
        let obj = {};
        let data = result.data;
        // obj.url = data.source_url;
        // console.log(this)
        obj.verifyBase64 = this.verifyBase64;
        obj.url = this.imgURLdomain + this.path + fileName;
        obj.fileName = fileName;
        typeof callback === 'function' && callback(obj);
      } else {
        alert('上传失败');
        Vue.$vux.loading.hide()
      }
    }

    // 上传失败回调
    let errorCallBack = (result = {}) => {
      Vue.$vux.loading.hide()
      alert('上传失败！请尝试在稳定网络环境上传！');
    }

    // 上传过程中回调
    let progressCallBack = (curr) => {
      Vue.$vux.loading.hide()
      // loading.text = `上传中: ${(curr * 100).toFixed(2)}%`
    }
  },
  compressImg: function(imgBase64, size, fileType, buildFile, uploadImg, maxHeight = 600, quality = 0.7){
		if(!imgBase64) return;
    let self = this
		let img = document.createElement('img');
		img.src = imgBase64;
		img.onload = function(){
		    var canvas = document.createElement('canvas');
		    var context = canvas.getContext('2d');
		    //压缩率设置
		    let s = size / 1024;
		    if(s < 50){
		    	maxHeight = img.height;
		    }else if(s >= 50 && s < 500){
		    	maxHeight = 600;
		    }else if(s >= 500 && s < 1024){
		    	maxHeight = 450;
		    }else if(s >= 1024 && s < 2*1024){
		    	maxHeight = 450;
		    } else if(s >= 2*1024 && s < 3*1024) {
		    	maxHeight = 450;
		    } else{
		    	maxHeight = 600;
		    }
		    if(img.height > maxHeight) {//按最大高度等比缩放
				img.width *= maxHeight / img.height;
				img.height = maxHeight;
			}
		    // canvas drawImage 参数
		    let sx = 0;
		    let sy = 0;
		    let sWidth = img.width;
		    let sHeight = img.height;
		    canvas.width = img.width;
		    canvas.height = img.height;

		    // canvas清屏
		    context.clearRect(0, 0, canvas.width, canvas.height)
        context.drawImage(img, sx, sy, sWidth, sHeight)
        // canvas.toBlob(file => {
        //   self.imgFile = file
        //   uploadImg && uploadImg()
        // }, 'image/jpeg', quality)
        let imgBase64 = canvas.toDataURL('image/jpeg', quality)
        buildFile && (self.imgFile = buildFile(imgBase64, fileType))
        uploadImg && uploadImg()
        return imgBase64
		}
	},
  convertBase64UrlToBlob: function (imgBase64, fileType){
    var bytes=window.atob(imgBase64.split(',')[1]) // 去掉url的头，并转换为byte
    //处理异常,将ascii码小于0的转换为大于0
    var ab = new ArrayBuffer(bytes.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
    }
    return new Blob( [ab] , {fileType});
  }
}

export default UploadFileByTXY;

/* eslint-enable */
